﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using BasicDataManagement;
using DataModel;
using SystemWindow;

namespace SystemWindow
{
    /// <summary>
    /// LoginWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        IOpertation op;
        SystemUser user;
        string cashierip;

        public LoginWindow()
        {
            InitializeComponent();
            op = OperationFactory.Create();
            XElement xmlfile = XElement.Load("Configuration.xml");
            cashierip = xmlfile.Element("ThisIP").Value;
        }

        private void BtnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (op.CheckUser(loginNumTB.Text, loginPwdTB.Password) == false)
            {
                MessageBox.Show("登录失败，请检查账号、密码，或网络配置错误");
                return;
            }
            int lastlogid = op.CheckLastLogout(loginNumTB.Text, cashierip);
            if (lastlogid != -1)
            {
                if (MessageBox.Show("检测到上次疑似为非正常退出，是否继续进行上次操作？", "确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    user = op.LoadLogRecord(lastlogid);
                    //op.DeleteLogoutRecord(user.StaffJobNum, cashierip);
                    SystemWindow.MainWindow form = new SystemWindow.MainWindow(user);
                    //form.Owner = this;
                    this.Hide();
                    form.Show();
                    this.Close();
                    return;
                }
                else
                {
                    op.DeleteLogoutRecord(loginNumTB.Text, cashierip);
                }
            }
            user = op.Login(loginNumTB.Text, loginPwdTB.Password, cashierip);
            if (user == null)
            {
                MessageBox.Show("登录失败，请检查账号、密码");
            }
            else
            {
                SystemWindow.MainWindow form = new SystemWindow.MainWindow(user);
                //form.Owner = this;
                this.Hide();
                form.Show();
                this.Close();
            }
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            loginNumTB.Focus();
        }
    }
}
